
import React, { Component, PropTypes } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import DataEditTable from '../../addons/DataEditTable'
import * as menuService from '../../../services/menus';
import { deepEqual } from '../../../utils/objects';
import * as indiDiviService from '../../../services/AccountDivi';

const daoName = "BaseYgjsTz";
const ButtonGroup = Button.Group;
const columns = [
  { title: '生效日期', width: 100, sorter: true, dataIndex: 'DTID', key: 'DTID', dispaly: true },
  { 
    title: '员工姓名', width: 100, sorter: true, key: 'EMID', dispaly: true,
    caption: "User.Name", render: data => data.User.Name, dispaly: true, filter: true  
  },
  { 
    title: '调整方向', width: 100, sorter: true, key: 'FX', 
    dataIndex: "FXNM", dispaly: true, filter: true 
  },
  { 
    title: '业务类型', width: 100, sorter: true, key: 'YWID', 
    dataIndex: "YWMC",  dispaly: true, filter: true 
  },
  { title: '日均基数(元)', width: 120, sorter: true, dataIndex: 'SDJS', key: 'SDJS', dispaly: true },
  { title: '时点基数(元)', width: 120, sorter: true, dataIndex: 'RJJS', key: 'RJJS', dispaly: true },
];
const controls = [
  { name: "DTID", label: "生效日期", type: "text", grid: 12 / 24, required: true },
  { 
    name: "EMID", label: "员工姓名", type: "select", grid: 12 / 24, required: true ,
    dataType: "number", fetch: { daoName: "User", optionTpl: 'Name', valueTpl: "ID" }
  },
  { 
    name: "YWID", label: "业务类型", type: "select", grid: 12 / 24, required: true,
    dataType: "number", fetch: { daoName: "ConfJsYwlx", optionTpl: 'YWMC', valueTpl: "ID" }
  },
  { name: "SDJS", label: "日均基数(元)", type: "number", grid: 12 / 24, required: true },
  { name: "RJJS", label: "时点基数(元)", type: "number", grid: 12 / 24, required: true },
]
const EditFrom = dataEditCreate(daoName);
class BaseYgjsTzForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      searchData: {},
      searchYwlx:{},
      diviDataSource: [],
      title: "",
      showEdit: false,
      isOK: 0
    };
  }
  componentWillReceiveProps(nextProps) {
    if (!deepEqual(nextProps.LSH, this.props.LSH)) {
      this.loadData(nextProps.LSH)
    }
  }  
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  componentDidMount() {
    this.loadData(this.props.LSH)    
    this.loadOptionData();
  }
  loadData(LSH) {
    let seeks = [];
    let whereItems = [];
    whereItems.push({
        FieldName: "LSH",
        Operator: "=",
        FieldValues: '' + LSH
      })
    seeks.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    this.state.diviDataSource = [];
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, seeks }
    });
  }
  searchHandle(data) {
    this.state.searchData = data
  }
  hideEditHandler() {
    this.props.dispatch({
      type: `${this.props.parentModel}/hideEdit`
    });
    const form = this.refs.diviForm.getForm();
    form.resetFields();
    this.setState({ diviDataSource: [] });
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  diviDel() {
    let keys = this.refs.table.getSelectedRowKeys();
    keys.sort();
    const datas = this.refs.table.state.datas;
    if (keys.length <= 0) {
      message.info('请选择删除的数据行！');
      return
    }
    let diviDsource = this.state.diviDataSource;
    if (diviDsource.length <= 0) {
      diviDsource = this.props.list;
    }
    for (let j = keys.length - 1; j >= 0; j--) {
      const k = keys[j]
      diviDsource.splice(k, 1)
    }
    this.setState({ diviDataSource: diviDsource })
  }
  diviSubmit() {
    const datas = this.refs.table.state.datas;
    let LSH = this.props.LSH;
    if (LSH ==='' || LSH === undefined){
      LSH='LS-'+datas[0].DTID+'-'
    }
    let avvlJS = 0;
    let sdJS = 0;
    let dataSource = []
    datas.map(d => {
      avvlJS = avvlJS + d.RJJS;
      sdJS=sdJS+d.SDJS;
      let data = {
        DTID: Number(d.DTID),
        EMID: Number(d.EMID),
        YWID: Number(d.YWID),
        SDJS: Number(d.SDJS),
        RJJS: Number(d.RJJS),
        LSH : LSH,
      }
      dataSource.push(data);
    })
    if (avvlJS !== 0 || sdJS !== 0) {
      message.info('时点基数和储蓄基数调入、调出总量必须一致！！！');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: `你确认要执行此调整操作吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        indiDiviService.IndiYgjsTzXz({LSH, dataSource }
        ).then(function (data) {
          if (data === 'OK') {
            message.success('基数调整成功！')
          } else {
            return;
          }
        }).catch(function (ex) {
          console.log('请求出错', ex)
        });
      }
    });
    const form = this.refs.diviForm.getForm();
    form.resetFields();
    this.props.dispatch({
      type: `${daoName}/setSelectedRowKeys`,
      payload: { selectedRowKeys: [] }
    });
  };
  DiviAdd() {
    const form = this.refs.diviForm.getForm();
    let isOK = true;
    let data = {};//空对象
    form.validateFields((err, values) => {
      if (!err) {
        if (values.DSDT === undefined || values.DSDT === '') {
          message.info('请选择生效日期信息！');
          isOK = false;
        } else if (values.EMID === undefined || values.EMID === '') {
          message.info('请选择调整基数的员工！');
          isOK = false;
        } else if (values.FX === undefined || values.FX === '') {
          message.info('请选择调整方向！');
          isOK = false;
        }  else if (values.YWID === undefined || values.YWID === '') {
          message.info('请选择业务类型！');
          isOK = false;
        }  else if (values.SDJS === undefined || values.SDJS === '') {
          message.info('请输入时点调整基数！');
          isOK = false;
        }  else if (values.RJJS === undefined || values.RJJS === '') {
          message.info('请输入日均调整基数！');
          isOK = false;
        } else {
          data.DTID = values.DSDT.get('year')+""+(values.DSDT.get('month')+1<10?""+values.DSDT.get('month')+1:values.DSDT.get('month')+1)+""
            +(values.DSDT.get('date')<10?"0"+values.DSDT.get('date'):values.DSDT.get('date'));
          data.EMID = Number(values.EMID);
          data.YWID = Number(values.YWID);
          data.FX = Number(values.FX);
          if (Number(values.FX)===1) {
            data.FXNM = '调入'
            data.SDJS=Number(values.SDJS);
            data.RJJS=Number(values.RJJS);
          }else {
            data.FXNM = '调出'
            data.SDJS=-Number(values.SDJS);
            data.RJJS=-Number(values.RJJS);
          }
        }
      }
    });
    if (!isOK) {
      return;
    }    
    let User ={
      Name :this.state.searchData.Name,
      EMID : this.state.searchData.ID
    } 
    let ywlx =this.props.optionDatas["ConfJsYwlx"];
    ywlx.map((m)=>{
      if(m.key===data.YWID){
        data.YWMC=m.label
      }
    });
    data.User=User;
    let diviDs = this.state.diviDataSource
    diviDs.push(data);
    this.setState({ diviDataSource: diviDs });
  }
  render() {
    let { list } = this.props
    list = this.state.diviDataSource.length <= 0 ? list : this.state.diviDataSource;
    const dsCount = this.state.diviDataSource.length
    const isDisabled = dsCount > 0 ? true : false;
    const controlsFilter = [
       {
        name: "EMID", label: "员工", type: "search", grid: 8 / 24, required: false,layout: { labelSpan: 10, wrapperSpan: 14 },
        dataType: "number", fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID", onSelect: this.searchHandle.bind(this) },
      }, {
        name: "FX", label: "调入/调出",  data: [{ value: '1', label: '调入' }, { value: '2', label: '调出' }], 
        grid: 8 / 24, type: "select",layout: { labelSpan: 12, wrapperSpan: 12 }
      },
      {
        name: "YWID", label: "业务类型", type: "select", grid: 8 / 24, required: false,
        layout: { labelSpan: 10, wrapperSpan: 14 }, isDisabled: isDisabled,
        dataType: "number", fetch: { daoName: "ConfJsYwlx", optionTpl: 'YWMC', valueTpl: "ID" }
      }, {
        name: "DSDT", label: "生效日期", type: "date", grid: 8 / 24, required: false, dataType: "date",
        layout: { labelSpan:10, wrapperSpan: 14 }, isDisabled: isDisabled
      },{
        name: "SDJS", label: "时点基数(元)", type: "number", grid: 8 / 24, dataType: "number",
        layout: { labelSpan: 12, wrapperSpan: 12 }
      }, {
        name: "RJJS", label: "日均基数(元)", type: "number", grid: 8 / 24, dataType: "number",
        layout: { labelSpan: 10, wrapperSpan: 14 }
      }, {
        name: 'XS', required: false, type: 'button-group',
        data: [{ value: '1', label: '新增', onClick: this.DiviAdd.bind(this) }, { value: '2', label: '删除', onClick: this.diviDel.bind(this) }],
        grid: 24 / 24, layout: { labelSpan: 7, wrapperSpan: 15 }
      },
    ];
    return (
      <Modal title={this.props.title} okText={"保存"} width={700} visible={this.props.showEdit} onCancel={this.hideEditHandler.bind(this)} onOk={this.diviSubmit.bind(this)} >
        <div className={styles.normal} style={{ background: '#fff', marginTop: -10, padding: '5px 5px' }}>
          <div>
            <div className={styles.create}>
              <EditFrom ref="diviForm" daoName={daoName} controls={controlsFilter} clearItemMargin={true} selectFirst={false} />
            </div>
            <DataEditTable ref="table" columns={columns} controls={controls} footer={true} dataSource={list}  multiSelect={true} />
          </div>
        </div>
      </Modal>
    )
  }

}

BaseYgjsTzForm.propTypes = {
  LSH: PropTypes.string,
  showEdit: PropTypes.bool,
  title: PropTypes.string,
  parentModel: PropTypes.string


};
BaseYgjsTzForm.defaultProps = {
  LSH: "",
  showEdit: false,
  title: "",
  parentModel: ""
};

function mapStateToProps(state) {
  const { list,optionDatas } = state[daoName];
  return {
    list,
    optionDatas
  }
}
BaseYgjsTzForm = connect(mapStateToProps)(BaseYgjsTzForm)
export default BaseYgjsTzForm;
